CS 116: Introduction to Computer Science 2

CS 116 Tutorial 6 (Solutions): Iteration

Reminders:

  • Midterm is on Monday, March 2nd, at 7:00 PM.
  • Assignment 6 is due Wed, March 11th at 10am.

Questions and Solutions

  1. Write a function all_same_type that consumes a list, called lst, and returns True if all members of that list are of the same type, else False.

    For example:
    all_same_type([2, 5, 3]) => True
    all_same_type([2, "R", 4.56]) => False

    Note that Python's built-in type function does not distinguish between types of lists: type([1,2]) == type(['a','b']) will return True.

    Solution:

    import check def all_same_type (lst): ''' returns True if all elements in lst are of the same type, and False otherwise all_same_type: (listof Any) -> Bool Examples: all_same_type ([]) => True all_same_type (["a"]) => True all_same_type (["a",1]) => False all_same_type (["a","b"]) => True ''' if lst != []: first_type = type(lst[0]) for item in lst: if type(item) != first_type: return False return True # Tests check.expect("Test 1", all_same_type([]), True) check.expect("Test 2", all_same_type(["a"]), True) check.expect("Test 3", all_same_type(["a",1]), False) check.expect("Test 4", all_same_type(["a","b"]), True) check.expect("Test 5", all_same_type([1,1.0]), False) check.expect("Test 6", all_same_type([[1,2],['b','c']]), True) check.expect("Test 7", all_same_type([1,2,3,4,5,6,7]), True) check.expect("Test 8", all_same_type([1,2,'3',[4],'5',6,7]), False)

  2. Write a Python function max_even_sum that consumes a nonempty list of lists of positive integers, lst. Evaluate in lst is a list of positive integers. It computes the sum of the even integers in each of the element lists in lst, and returns the largest out of these sums. If a sublist contains no even integers, its sum is zero.

    For example:
    max_even_sum([[], [3], [2,4,6]]) => 12

    Solution:

    import check def max_even_sum(lst): ''' calculates the sum of even values in each row of lst, and returns the largest such sum. If a sublist contains no even integers, its sum is 0. max_even_sum: (listof (listof Int)) -> Int requires: each element of lst is a list of integers which are >= 0 and lst is non-empty Examples: max_even_sum([[]]) => 0 max_even_sum([[3,1]]) => 0 max_even_sum([[2],[7]]) => 2 max_even_sum([[4,2,5],[9,8,9]]) => 8 ''' ans = 0 for sublist in lst: subtotal = 0 for i in sublist: if i%2==0: subtotal += i ans = max(subtotal, ans) return ans # Tests for max_sum check.expect("Test 1", max_even_sum([[]]), 0) check.expect("Test 2", max_even_sum([[1,7,3]]), 0) check.expect("Test 3", max_even_sum([[2,4]]), 6) check.expect("Test 3", max_even_sum([[2,3,4]]), 6) check.expect("Test 4", max_even_sum([[2],[7,9],[4,4]]), 8) check.expect("Test 5", max_even_sum([[4,2,5],[9,8,9],[2,3,4,99], [10]]), 10)
  3. Write a Python function sum_digits that consumes a Nat (called n), and returns a number represents the summation of its digits.

    For examples:
    sum_digits(1)=>1
    sum_digits(55)=>10

    Solution:

    import check
    
    def sum_digits(n):
        '''
        returns the sum of all digits in n.
        
        sum_digits: Nat -> Nat
        
        Examples:
        sum_digits(0) => 0
        sum_digits(1) => 1
        sum_digits(55) => 10
        '''
        acc = 0
        for digits in str(n):
    	    acc += int(digits)
        return acc
    	
    # Tests for sum_digits
    check.expect("Test 1", sum_digits(0),0)
    check.expect("Test 2", sum_digits(1),1)
    check.expect("Test 3", sum_digits(11),2)
    check.expect("Test 4", sum_digits(22),4)
    check.expect("Test 5", sum_digits(2590),16)
    check.expect("Test 6", sum_digits(99999999),72)
    	
    

  4. Write a Python function that consumes a natural number n and returns a list of strings. The returned list will look like

    ["", "1", "22", "333", "4444", "55555", ... , "nnnnn...nnnn"]
    

    where the last element is the number n repeated n times.

    For examples:
    make_list(0) => [""]
    make_list(3) => ["", "1", "22", "333"]

    Solution:

    import check
    
    
    def make_list(n):
        '''
        consumes a Nat, n, and returns a list of strings
        , "", "1", "22", ..., "nnnn...nn" (n times)
        
        make_list: Nat -> (listof Str)
    
        Examples:
        make_list(0) => [""]
        make_list(1) => ["", "1"]
        make_list(5) => ["", "1", "22", "333", "4444", "55555"]
        '''
        lst = []
        for i in range(n+1):
            lst.append(str(i) * i)
        return lst
    
    # Tests
    check.expect("Test 1", make_list(0), [""])
    check.expect("Test 2", make_list(1), ["", "1"])
    check.expect("Test 3", make_list(3), ["", "1", "22", "333"])
    check.expect("Test 4", make_list(6), ["", "1", "22", "333", "4444", "55555", "666666"])
    
    

  5. Write a function called valid_input that consumes a string to be used as the prompt, prompt, and a list of strings of valid inputs, valid, and a positive integer max_guess.
    The function should continuously prompt the user for input until the user enters a value in the list valid, and then returns that value, or print a message when maximum number of guess is reached. If the user enters an invalid value, the function will let them know by printing: "Invalid input. Try again." to the screen. If maximum number of guess is reached, the function will print "Maximum number of guess is reached"

    For example:
    If the user enters "6", "5", and "3", valid_input("Enter a digit < 5: ", ["0", "1", "2", "3", "4"], 5) => "3" and the following is printed:
    Enter a digit < 5: 6
    Invalid input. Try again
    Enter a digit < 5: 5
    Invalid input. Try again
    Enter a digit < 5: 3

    Note: You may assume that the user enters input that is the correct type.

    Solution:

    import check def valid_input(prompt, valid, max_guess): ''' returns the first string in valid entered by the user when prompted by prompt unless the number of guesses the user makes reaches the maximum number of guesses, max_guess. In this case, the string Maximum number of guess is reached". If the user enters a value that is not in valid, the string "Invalid prompt. Try again." is printed and they are prompted by prompt again. Effects: * Prompts the user for type of data to enter, and reads in the choice. This process is repeated until the user enters one of the values in valid. * Prints a message if the value entered is invalid and prints a message if the maximum number of guesses is reached. valid_input: Str (listof Str) Nat -> Str requires: valid is a non-empty list Examples: When valid_input("Will you pass CS116? ", ["yes", "no"], 2) is called and the user inputs "maybe", then "Invalid input. try again" is printed and the user is prompted again. Then the user enters "i don't know" and "Maximum number of guess is reached" is printed. Nothing is returned. When valid_input("Who was Prime Minister in 2008? ", ['Harper'], 2) is called and the user enters "Harper", "Harper" is returned. ''' value = input(prompt) count = 1 while not(value in valid) and count < max_guess: print("Invalid input. Try again.") value = input(prompt) count = count + 1 if value in valid: return value elif count >= max_guess: print("Maximum number of guess is reached") # Tests for valid_input check.set_input(["42"]) check.expect("Test 1", valid_input("What is the answer to the ultimate question? ", ["42"], 5), "42") check.set_input(["no","five","9","cat","snow","Pi Day"]) check.set_screen("5x 'Invalid input. Try again.'") check.expect("Test 2", valid_input("What day is March 14th? ", ["Pi Day"], 10), "Pi Day") check.set_input(["yellow"]) check.set_screen(["Invalid input. Try again.", "Maximum number of guess is reached"]) check.expect("Test 3", valid_input("Name a colour on the Italian flag: ", ["green","white","red"], 1), None) check.set_input(["yellow", "apple", "blue"]) check.set_screen(["Invalid input. Try again.", "Maximum number of guess is reached"]) check.expect("Test 4", valid_input("Name a colour on the Canadian flag: ", ["white","red"], 3), None)

Valid XHTML 1.0 Strict

Last modified on Friday, 28 February 2020, at 15:27.